package com.example.my0609projects;

import java.io.IOException;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class HttpUtil {
    /*
    连接网络
     */
    public String connectServer() throws IOException {
        String url="http://v.juhe.cn/toutiao/index?key=f5c521bc79d013645e9d07592aa88aaa";
        //获取网络连接对象
        OkHttpClient client=new OkHttpClient();
        //获取请求体
        RequestBody body = new FormBody.Builder().build();
        //获取请求
        Request build = new Request.Builder().post(body).url(url).build();
        //发送请求，把Request发给服务器，获取服务器返回的响应,此方法必须执行在子线程
        Response response=client.newCall(build).execute();
        if (response.isSuccessful()){
            //获取响应中的数据，并转成String
            String data=response.body().string();
            return data;
        }else{
            throw new IllegalAccessError("获取网路数据失败");
        }

    }
}
